<template>
    <div>
      <van-pull-refresh v-model="refreshing" @refresh="onRefresh">
          <van-list
          v-model="loading"
          :finished="finished"
          finished-text="没有更多了"
          @load="onLoad"
          offset="50"
          :immediate-check="false"
          >
            <article-Item v-for="item in articleList" :key="item.art_id" :artobj="item"
            @dislike="dislikeArt"
            @reports="reportsFn"
            @click.native="goArticleDetail(item.art_id)"
            ></article-Item>
          </van-list>
        </van-pull-refresh>
    </div>
</template>

<script>
import { getArticleListAPI, dislikeAPI, articleReportsAPI } from '@/api'
import ArticleItem from '@/components/ArticleItem.vue'
import { Notify } from 'vant'
export default {
  components: {
    ArticleItem
  },
  props: ['articleId'],
  data () {
    return {
      articleList: [],
      loading: false,
      finished: false,
      nextTime: null,
      refreshing: false
    }
  },
  created () {
    this.getArticleList()
  },
  methods: {
    // 获取文章列表
    async getArticleList () {
      this.loading = true
      const { data: res } = await getArticleListAPI({
        channel_id: this.articleId,
        timestamp: this.nextTime
      })

      // 把下一次的时间戳存放到nextTime，到底部进行加载的时候用这个时间戳去请求（类似于懒加载）
      this.nextTime = res.data.pre_timestamp
      this.articleList = [...this.articleList, ...res.data.results]
      // console.log(res.data)
      // 如果不关闭，底部会一直处于加载状态
      this.loading = false
      // 如果接收回来的数据没有时间戳，说明没有数据了，就不需要发起请求了
      if (res.data.results.pre_timestamp === null) {
        this.finished = true
      }
      this.loading = false
    },

    onLoad () {
      if (this.articleList.length > 0) { this.getArticleList() }
    },

    onRefresh () {
      // 清空列表数据
      this.articleList = []
      // 让刷新加载为false
      this.refreshing = false
      // 时间为当前系统时间
      this.nextTime = null
      // 重新发起请求
      this.getArticleList()
      this.finished = false
      // 将 loading 设置为 true，表示处于加载状态
      this.loading = true
    },

    // 对文章不感兴趣
    async dislikeArt (obj) {
      console.log(obj)
      await dislikeAPI({
        target: obj.art_id
      })
      Notify({
        type: 'success',
        message: '反馈成功'
      })
    },

    // 举报文章
    async reportsFn (obj) {
      await articleReportsAPI(obj)
      Notify({
        type: 'success',
        message: '举报成功'
      })
    },

    // 文章详情页
    goArticleDetail (id) {
      this.$router.push(`/detail?id=${id}`)
    }
  }

}
</script>
